package com.googlecode.project.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: DataInsertionServlet
 * 
 */
public class DataInsertionServlet extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	public String computerName() throws UnknownHostException {
		return InetAddress.getLocalHost().getHostAddress();
	}

	public String dateFormat() {
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		java.util.Date date = new java.util.Date();
		String datetime = dateFormat.format(date);
		return datetime;
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public DataInsertionServlet() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String connectionURL = "jdbc:derby:/DerbyDB/AssetDB";
		Connection conn = null;
		ResultSet rs;
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		int numRowsChanged;
		String inet = request.getRemoteAddr();
		System.out.println(inet);
		boolean viewed = false;

		try {
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
			conn = DriverManager.getConnection(connectionURL);
			Statement sel = conn.createStatement();
			rs = sel.executeQuery("SELECT MAX(QUERY) FROM REQUEST_DETAILS");
			int currentRequest = 0;
			while (rs.next()) {
				currentRequest = rs.getInt(1);
			}

			String sql = "INSERT INTO REQUEST_DETAILS VALUES (?,?,?,?,?,?,?,?,?,?)";
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setInt(1, currentRequest + 1);
			pst.setString(2, title);
			pst.setString(3, description);
			pst.setString(4, inet);
			pst.setString(5, dateFormat());
			pst.setBoolean(6, viewed);
			int currentInet = 1;
			rs = sel.executeQuery(executeInetFinder(inet));
			while (rs.next()) {
				currentInet = rs.getInt(1);
				if (currentInet == 0) {
					currentInet = 1;
				}
			}
			pst.setInt(7, currentInet);
			pst.setInt(8, 100 / currentInet);
			pst.setString(9, "Unchecked");
			pst.setInt(10, 1);

			numRowsChanged = pst.executeUpdate();

			HTMLOutputMethod(out, title, description);

		} catch (Exception e) {
			out.println(e);
		} finally {
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException ignored) {
				out.println(ignored);
			}
		}
	}

	/**
	 * @param inet
	 * @return
	 */
	public String executeInetFinder(String inet) {
		return "SELECT COUNT(IP_ADDRESS) FROM REQUEST_DETAILS WHERE IP_ADDRESS = '"
				+ inet + "'";
	}

	public void HTMLOutputMethod(PrintWriter out, String title,
			String description) {
		out.println("<html>");
		out.println("<head>");
		out.println("<title>The Mobile Teaching Assistant's Assistant</title>");
		// out.println("<meta http-equiv='Content-Type' content='text/html;
		// charset=UTF-8' />");
		out.println("<link rel=stylesheet href='style.css' type='text/css'>");
		out.println("</head>");
		out.println("<body id='twocolumn-left'>");
		out.println("<div id='container'>");
		out.println("<div class='wrapper'>");
		out.println("<div id='header'>");
		out.println("<div class='wrapper'>");
		out
				.println("<h1 id='page-title'><div id='g_title'><div style='text-align: center;'>The Mobile Teaching Assistant's Assistant<br></div></div></h1>");
		out.println("<div style='clear: both'></div>");
		out
				.println("<p class='description'/><div id='g_description'><p style='text-align: center;'/>|    <a href='index.html'>Home</a>    |    <a href='http://www.ucd.ie'>ucd.ie</a>    |    <a href='requests.jsp'>Student Requests</a>    |    Help    |<br></div>");
		out.println("<div style='clear: both'></div>");
		out.println("</div>");
		out.println("</div>");
		out.println("<div id='main-content'>");
		out.println("<div class='wrapper'>");
		out
				.println("<div class='content-item'><div id='g_body'><p style='text-align: justify; font-family: verdana;'><font size='2'></font></p></div></div>");
		out.println("<h2>Thank you for submitting your query.</h2>\n");
		out.println("<h4>The Title you entered is as follows:</h4>");
		out.println(title);
		out.println("<h4>The Description you entered is as follows:</h4>");
		out.println(description);
		out.println("<div style='clear: both'></div>");
		out.println("</div>");
		out.println("</div>");
		out.println("<div id='sidebar'>");
		out.println("<div class='wrapper'>");
		out.println("<div class='links'>");
		out
				.println("<div class='wrapper'><div id='g_sidebar'><p style='text-align: justify;'> <span style='font-family: verdana;'>Supervisors who wish to make use of the advanced functions of this application should click here to login with their username and password.</span><br></p></div></div>");
		out.println("<div style='clear: both'></div>");
		out.println("</div>");
		out.println("</div>");
		out.println("</div>");
		out.println("<div id='footer'><div class='wrapper'>");
		out.println("<hr />");
		out
				.println("<p><div id='g_footer'><p style='text-align: center;'/>UCD School of Computer Science & Informatics <br></div>");
		out.println("<div style='clear: both'></div>");
		out.println("</div></div>");
		out.println("<!-- /wrapper --><!-- /footer -->");
		out.println("</div>");
		out.println("</div>");
		out
				.println("<div id='extraDiv1'><span></span></div><div id='extraDiv2'><span></span></div>");
		out
				.println("<div id='extraDiv3'><span></span></div><div id='extraDiv4'><span></span></div>");
		out
				.println("<div id='extraDiv5'><span></span></div><div id='extraDiv6'><span></span></div>");
		out.println("</body>");
		out.println("</html>");
	}
}